package cn.cqone.crm.controller;

import cn.cqone.crm.domain.Employee;
import cn.cqone.crm.utils.JSONResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@Controller
@RequestMapping("system")
public class LoginController {


    @Autowired
    private  SecurityManager securityManager;
    @ResponseBody
    @CrossOrigin
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public JSONResult login(@RequestBody Employee employee) {
        Subject subject = SecurityUtils.getSubject();
        try {
            //放入Shiro的上下文

            SecurityUtils.setSecurityManager(securityManager);

            if (!subject.isAuthenticated()) {
                //如果未登录，就登录一下
                UsernamePasswordToken token = new UsernamePasswordToken(employee.getUsername(), employee.getPassword());
                subject.login(token);

            }
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return JSONResult.error("用户名不存在！");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return JSONResult.error("密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return JSONResult.error("连接超时");
        }
        Employee employee1=(Employee) subject.getPrincipal();
        employee.setPassword(null);
        Map<String,Object> result=new HashMap<>();
        result.put("user",employee1);
        result.put("token",subject.getSession().getId());
        JSONResult jsonResult=new JSONResult();
        jsonResult.setData(result);
        return jsonResult;
     }

    @RequestMapping(value="/logout",method = RequestMethod.GET)
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            subject.logout();
        }
        return "login";
    }

}
